package de.grosjohann.android.feuerwehr.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import de.grosjohann.android.feuerwehr.IUpdateUIListener;
import de.grosjohann.android.feuerwehr.util.FileUtil;
import de.grosjohann.android.feuerwehr.webservice.FMSWsFacade;

public class FMSUpdateService
  extends IntentService {

  public static final String FMS_STATUS_KENNUNG = "feuerwehr.FMSStatusKennung";
  public static final String FMS_STATUS_DATA = "feuerwehr.FMSStatusData";
  public static final String FMS_LOC_DATA = "feuerwehr.FMSLocationData";
  public static final String FMS_STATUS_ERROR = "feuerwehr.FMSStatusError";

  private static final String NAME = "FMSUpdateService";

  public static IUpdateUIListener updateUIListener;

  public FMSUpdateService() {
    super(NAME);
  }

  @Override
  protected void onHandleIntent(Intent intent) {

    Log.d(NAME, "handle");

    Context context = getApplicationContext();

    Bundle bundle = intent.getExtras();

    if (bundle != null) {
      String auth = bundle.getString(FMSAuthService.FMS_AUTHORIZATION);
      String identifier = bundle.getString(FMSUpdateService.FMS_STATUS_KENNUNG);

      String status = null;
      String loc = null;

      if (bundle.containsKey(FMSUpdateService.FMS_STATUS_DATA)) {
        status = bundle.getString(FMSUpdateService.FMS_STATUS_DATA);
      }

      if (bundle.containsKey(FMSUpdateService.FMS_LOC_DATA)) {
        loc = bundle.getString(FMSUpdateService.FMS_LOC_DATA);
      }

      try {

        String json = FMSWsFacade.setFMSStatusAndLocation(context, auth, identifier, status, loc);

        FileUtil.writeFile(context, FMS_STATUS_DATA, json);

        if (updateUIListener != null) {
          updateUIListener.showInfo("");
        }
      } catch (Exception ex) {
        Log.e(NAME, ex.getMessage(), ex);
        if (updateUIListener != null) {
          updateUIListener.showError("");
        }

      }
    }
  }
}
